import React, { useEffect, useRef, useState } from "react";
import {
  ActivityIndicator,
  FlatList,
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Dimensions,
  Image,
  ScrollView, NativeModules,
} from "react-native";
import ListItem from "../ListDetail/ListItem";
import Colors from "../../util/Colors";
import { FAB } from "@rneui/base";
import AntDesign from "react-native-vector-icons/AntDesign";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import Toast from "react-native-easy-toast";


export default function(props) {

  let list = props.route.params.list;
  let [lists,setLists] = useState([]);
  const toast = useRef(null);
  useEffect(() => {
    NativeModules.ToolModule.getListSongs(list.id).then((r) => {
     let result = JSON.parse(r.songs);
      //console.log(result);
      if(!result){
        toast.current.show('列表为空！')
        // props.navigation.pop();
      }
      setLists(result);
    })
  },[])

  function del(item){
    let newList = [];
    for (const l of lists) {
      if(l.name !== item.name || l.from !== item.from){
        newList.push(l);
      }
    }
    lists = newList;
    setLists(newList);
    asySongs();
  }
  function asySongs(){
    //console.log('开始同步歌单:' + list.name);
    NativeModules.ToolModule.addListSong(list.id,JSON.stringify(lists)).then((r) => {
      //console.log(r);
    })
  }
  const _onItemPress = item => {
      props.add(item);
      props.play(item);
    // props.navigation.navigate('MusicPlayer', {song: item});
  };

  const _getItemLayout = (data, index) => ({
    length: itemHeight,
    offset: itemHeight * index,
    index,
  });

  const _renderItem = ({index,item}) => {

      return(
        <TouchableOpacity onPress={_onItemPress}>
          <View style={styles.item}>
            {item.img && !props.isAlbum?
              <Image
                roundAsCircle={true}
                source={{uri:item.img}}
                style={{width: 60, height: 60, borderRadius: 6}}
              />
              :
              <View/>
            }

            <View style={styles.layoutText}>
              <Text style={styles.itemTitle} numberOfLines={1}>
                {item['name']}
              </Text>
              <Text style={styles.itemSubTitle} numberOfLines={1}>
                {item.singer}
              </Text>
            </ View>
            <TouchableOpacity style={{ marginRight: 10 }} onPress={() => del(item)}>
              <MaterialCommunityIcons size={30} name={'playlist-remove'} />
            </TouchableOpacity>
          </View>
        </TouchableOpacity>
      )
  };
  function pressListBtn(){
    props.addPlayList(lists);
    props.setCurrentMusic(lists[0]);
  }
  function getUri(){
    if(lists && lists[0]){
      return{
        uri:lists[0].img
      }
    }else {
      return require('../../images/music_cover.jpg')
    }
  }
  return (
    <View style={styles.container}>
      <Toast
        ref={toast}
        position="center"
        style={{ backgroundColor: Colors.colorPrimary }}
      />
      <ScrollView>
          <Image source={getUri()}
                 style={{width:width,height:height/3}}
          >
          </Image>
          <FAB
            color={Colors.colorLight}
            visible={true}
            icon={<AntDesign name={'caretright'} color={'white'} style={{marginBottom:-4}} size={27}/>}
            size="large"
            style={{ position:'absolute',right:10,top:height/3 - 40 }}
            onPress={pressListBtn}
          />
          <View style={{backgroundColor:'rgba(255,255,255,0.11)',width:width,position:'absolute'}}>

            <TouchableOpacity onPress={()=>props.navigation.pop()}>
              <AntDesign name={'left'} style={{marginLeft:10}} size={35} color={'white'}/>
            </TouchableOpacity>
          </View>
        <FlatList
          data={lists}
          renderItem={_renderItem}
          keyExtractor={(item, index) => index.toString()}
          getItemLayout={_getItemLayout}
        />
      </ScrollView>

    </View>
  );

}

const itemHeight = 70; // 如果可以确定高度，免去了渲染计算高度
const {height, width} = Dimensions.get('window');
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  /* separator: {
    width: screen.width - 20,
    height: 1,
    alignSelf: 'center',
    backgroundColor: '#eeeeee',
    borderStyle: 'dotted',
  }, */
  item: {
    flex: 1,
    flexDirection: 'row',
    //backgroundColor: "#eeeeee",
    justifyContent: 'space-around', // 子元素沿主轴的对齐方式
    marginHorizontal: 10,
    marginVertical: 5,
    //padding: 10,
    // borderRadius: 4,    // 圆角
    // shadowColor: 'grey', // 添加阴影效果
    shadowOffset: {width: 1, height: 1},
    shadowOpacity: 0.5,
    shadowRadius: 2,
    elevation: 2,  // android端要加上这个属性，不然阴影不出来
  },
  layoutText: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center', // 子元素沿主轴的对齐方式
    marginLeft: 10,
    overflow: 'hidden'
    //padding: 10
  },
  itemTitle: {
    fontSize: 16,
  },
  itemSubTitle: {
    fontSize: 14,
    color: '#aaaaaa',
    marginTop: 2,
  },
});
